package key.dao.impl;


import key.dao.UserDao;
import key.entity.User;
import key.util.Constants;
import key.util.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * 数据库访问实现类
 */
@SuppressWarnings("all")
public class UserDaoImpl implements UserDao {

    @Override
    public User selectUserByUname(String username) throws SQLException {
        //1.创建一个QueryRunner对象
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
        //2.执行sql语句
        String sql = "select u_id uid , u_name username , u_password upassword" +
                ", u_sex usex , u_status ustatus , u_code code , u_email email " +
                ", u_role urole from user where u_name = ?";
        User user = queryRunner.query(sql, new BeanHandler<>(User.class), username);
        return user;
    }

    @Override
    public int insertUser(User user) throws SQLException {
        //1.创建一个QueryRunner对象
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

        //2.插入数据
        String sql = "insert into user (u_name,u_password,u_sex,u_status," +
                "u_code,u_email,u_role) value (?,?,?,?,?,?,?)";

        int rows = queryRunner.update(sql, user.getUsername(), user.getUpassword(),
                user.getUsex(), user.getUstatus(),
                user.getCode(), user.getEmail(), user.getUrole());
        return rows;
    }

    @Override
    public User selectUserByCode(String code) throws SQLException {

        //1.创建一个QueryRunner对象
        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());
        //2.执行sql语句
        String sql = "select u_id uid , u_name username , u_password upassword" +
                ", u_sex usex , u_status ustatus , u_code code , u_email email " +
                ", u_role urole from user where u_code = ?";
        User user = queryRunner.query(sql, new BeanHandler<>(User.class), code);
        return user;
    }

    @Override
    public int updateStatusByUid(int uid) throws SQLException {

        QueryRunner queryRunner = new QueryRunner(DbUtils.getDataSource());

        String sql = "update user set u_status = ? where u_id = ?";

        int row = queryRunner.update(sql, Constants.USER_ACTIVE, uid);
        return row;
    }
}
